/**
 *Project: jh-framework
 *File: cn.xkshow.util.HED.java 
 *Author: admin@xkshow.cn with the copyrite
 ****************************************************************
 *   VERSION       DATE            BY       CHANGE/COMMENT
 * --------------------------------------------------------------
 *    1.0        2013-1-27        xkshow.cn         create
 ****************************************************************
 *note: 
 *  Hardy-Encoder-Decoder
 ***************************************************************/
package cn.xkshow.util.security;

import java.io.IOException;

import cn.xkshow.lang.StringHelper;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class HED {
	/*
	 * Enc
	 */
	public static String encode(String coderstr) {
		if (!StringHelper.isNotNull(coderstr))
			return null;

		coderstr = new BASE64Encoder().encode(coderstr.getBytes());
		coderstr = clearNewline(coderstr.toString());// no Newline

		return StringHelper.swapComplex(StringHelper.swapOddEven(coderstr));
	}

	/*
	 * Dec
	 */
	public static String decode(String coderstr) {
		try {
			if (!StringHelper.isNotNull(coderstr))
				return null;

			coderstr = StringHelper.swapOddEven(StringHelper.swapComplex(coderstr));
			coderstr = new String(new BASE64Decoder().decodeBuffer(coderstr));
		} catch (IOException e) {
			System.out.println("Exception with the Decryption!");
			return null;
		}
		return coderstr;
	}

	private static String clearNewline(String coderstr) {// 因为base64每76字符自动换行，此方法可禁止换行
		StringBuffer sb = new StringBuffer(coderstr.length());
		for (int i = 0; i < coderstr.length(); i++) {
			if (coderstr.charAt(i) != 10 && coderstr.charAt(i) != 13) {
				sb.append(coderstr.subSequence(i, i + 1));
			}
		}
		return sb.toString();
	}

	public static void t(String coderstr) {
		System.out.print("Original:" + coderstr);

		coderstr = HED.encode(coderstr);
		System.out.println(" ====>>Encoder:" + coderstr);

		coderstr = HED.decode(coderstr);
		System.out.println(" Decoder:" + coderstr);

		System.out.println("--------------------------");
	}

}
